import { switchCompany } from '@/services/api';
import { fetchMailPrompt, fetchPullList } from '@/services/mail';
import { getMsgCount } from '@/services/message';
import { getNewFunctionCount } from '@/services/newFunction';
import { fetchSelfTaskCount } from '@/services/notice/homePage';
import { getTaskCount } from '@/services/task';
/* eslint-disable no-nested-ternary */
import { queryNotices } from '@/services/user';
import { getFlatterMenu } from '@/utils/auth/helper';
import pageTabUtil from '@/utils/pageTabUtil';
import { parseLocation } from '@/utils/utils';

export default {
    namespace: 'global',

    state: {
        collapsed: false,
        notices: [],
        noticeCount: 0,
        mailPromptCount: [],
        taskCount: {
            toExecuteTaskNum: 0,
            toAuditTaskNum: 0,
            toAcceptTaskNum: 0,
            toEstimateTaskNum: 0,
            toScoreTaskNum: 0
        },
        userTask: {
            unFinishCount: 0,
            finishCount: 0
        },
        welcomeEnable: false // 判断是否是首次登陆
    },

    effects: {
        *fetchNotices(_, { call, put, select }) {
            const data = yield call(queryNotices);
            yield put({
                type: 'saveNotices',
                payload: data
            });
            const unreadCount = yield select(state => state.global.notices.filter(item => !item.read).length);
            yield put({
                type: 'user/changeNotifyCount',
                payload: {
                    totalCount: data.length,
                    unreadCount
                }
            });
        },
        *clearNotices({ payload }, { put, select }) {
            yield put({
                type: 'saveClearedNotices',
                payload
            });
            const count = yield select(state => state.global.notices.length);
            const unreadCount = yield select(state => state.global.notices.filter(item => !item.read).length);
            yield put({
                type: 'user/changeNotifyCount',
                payload: {
                    totalCount: count,
                    unreadCount
                }
            });
        },
        *changeNoticeReadState({ payload }, { put, select }) {
            const notices = yield select(state =>
                state.global.notices.map(item => {
                    const notice = { ...item };
                    if (notice.id === payload) {
                        notice.read = true;
                    }
                    return notice;
                })
            );
            yield put({
                type: 'saveNotices',
                payload: notices
            });
            yield put({
                type: 'user/changeNotifyCount',
                payload: {
                    totalCount: notices.length,
                    unreadCount: notices.filter(item => !item.read).length
                }
            });
        },
        *switchCompany({ payload }, { call }) {
            yield call(switchCompany, payload.firstCompanyCode);
            // 貌似现在切换后都会刷新页面，因此不需要后面的逻辑，先注掉
            // 切换公司后需要改变当前用户信息的公司和部门ID
            // if (response.code === 10000) {
            //     const { postRank, departmentId } = response.data;
            //     const currentUser = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};
            //     localStorage.setItem(
            //         'user',
            //         JSON.stringify({
            //             ...currentUser,
            //             companyId: response.data.companyId,
            //             departmentId: postRank === 0 ? (departmentId !== 'null' ? departmentId : undefined) : undefined
            //         })
            //     );
            // }
        },
        *getMsgCount({ payload, callback }, { call, put }) {
            const response = yield call(getMsgCount, payload);
            if (response.code === 10000) {
                yield put({
                    type: 'save',
                    payload: {
                        noticeCount: response?.data?.unReadStateCount || 0
                    }
                });
            }
            if (callback) callback(response);
        },

        *getSelfTaskCount(_, { put, call }) {
            const result = yield call(fetchSelfTaskCount);
            if (result?.code === 10000) {
                yield put({
                    type: 'save',
                    payload: {
                        userTask: result.data
                    }
                });
            }
        },

        // 获取邮箱提示信息
        *fetchMailPrompt({ payload, callback }, { call, put }) {
            const response = yield call(fetchMailPrompt, payload);
            if (response.code === 10000) {
                yield put({
                    type: 'save',
                    payload: {
                        mailPromptCount: response.data
                    }
                });
            }
            if (callback) callback(response);
        },
        // 同步邮箱邮件
        *fetchPullList({ payload, callback }, { call }) {
            const response = yield call(fetchPullList, payload || {});
            if (callback) callback(response);
        },
        *fetchTaskCount({ payload, callback }, { call, put }) {
            const response = yield call(getTaskCount, payload);
            if (response.code === 10000) {
                const { data } = response;
                yield put({
                    type: 'saveTaskCount',
                    payload: data
                });
            }
            if (callback) callback(response);
        },
        *fetchNewFunctionCount({ callback }, { call, put }) {
            const response = yield call(getNewFunctionCount);
            if (response.code === 10000) {
                const { data } = response;
                yield put({
                    type: 'saveNewFunctionCount',
                    payload: data
                });
            }
            if (callback) callback(response);
        }
    },

    reducers: {
        changeLayoutCollapsed(state, { payload }) {
            return {
                ...state,
                collapsed: payload
            };
        },
        saveNotices(state, { payload }) {
            return {
                ...state,
                notices: payload
            };
        },
        saveClearedNotices(state, { payload }) {
            return {
                ...state,
                notices: state.notices.filter(item => item.type !== payload)
            };
        },
        save(state, { payload }) {
            return {
                ...state,
                ...payload
            };
        },
        // 初始化菜单数量
        clearPropmtCounts(state) {
            return {
                ...state,
                myCount: [],
                adviseCount: [],
                mailPromptCount: []
            };
        },
        saveTaskCount(state, { payload }) {
            return {
                ...state,
                taskCount: payload
            };
        },
        saveNewFunctionCount(state, { payload }) {
            return {
                ...state,
                newFunctionCount: payload
            };
        }
    },

    subscriptions: {
        setup({ history }) {
            // Subscribe history(url) change, trigger `load` action if pathname is `/`
            return history.listen(({ pathname: originPathname, query: originQuery, search, state }) => {
                // before route change
                const { action } = history;
                const flatterMenu = getFlatterMenu();
                // 兼容router push string url的情况
                const [pathname, query] = parseLocation({ pathname: originPathname, query: originQuery });
                // 是否配置为新页签打开
                const { openTab } = flatterMenu[pathname] ?? {};
                // 是否和当前页面是同一个路由...根据经验不应该打开新页签...越来越多的隐含条件
                const isSameRoute = parseLocation({ pathname: pageTabUtil.currentKey ?? '' })[0] === pathname;
                const extraState = openTab && !isSameRoute ? { tabRoute: true, tabRefresh: true } : {};
                pageTabUtil.onBeforeRouteChange({
                    pathname,
                    state: { ...extraState, ...state },
                    query,
                    action,
                    flatterMenu
                });
                if (typeof window.ga !== 'undefined') {
                    window.ga('send', 'pageview', pathname + search);
                }
            });
        }
    }
};
